//
//  AppDelegate.m
//  SecondLoan
//
//  Created by 姚永波 on 2019/8/18.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "AppDelegate.h"
#import "MainTabViewController.h"
#import <ifaddrs.h>
#import <net/if.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import "UserInfo.h"
#import "WebSocketManager.h"
#import <Contacts/Contacts.h>
#import <UserNotifications/UserNotifications.h>
#import "SystemDeviceTool.h"
#import "SLMessageDetailViewController.h"
#import "ZJPhoneIPAddress.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTCellularData.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import "CDPAuth.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate>
{
    UIBackgroundTaskIdentifier _backIden;
}
@property (nonatomic, assign) NSInteger number;
@property (nonatomic, strong) NSTimer   *timer;
@property (strong, nonatomic) NSString *netconnType;
@end
static AppDelegate *__delegate = nil;

@implementation AppDelegate
AppDelegate* getDelegate(void){
    return __delegate;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    self.isNetworkConnenct = YES;
    [self setupNetwork];
    // 设置主窗口,并设置根控制器
    self.window = [[UIWindow alloc]init];
    self.window.frame = [UIScreen mainScreen].bounds;
    MainTabViewController *tab = [[MainTabViewController alloc] init];
    MainNavigationController *nav = [[MainNavigationController alloc] initWithRootViewController:tab];
    _masterNavigationController = nav;
    nav.navigationBar.hidden = YES;
    self.window.rootViewController = _masterNavigationController;
    [self.window makeKeyAndVisible];
    __delegate = self;
    [GDSNSManager registerApp];
    [self registerAPN];
    [self registerOCR];
    [[WebSocketManager shareInstance] setSocketOpen];
    [NSThread sleepForTimeInterval:2.0];
    return YES;
}

- (void)registerOCR{
    [CDPAuth initializeWithMembershipkey:OCR_APPKEY handler:^(BOOL success, NSError *error, NSDictionary *result) {
        if (success) {
            debugLog(@"CDPAuth successed");
        }else {
            debugLog(@"CDPAuth failed");
        }
    }];
}
- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier
{
    return NO;
}
// 注册通知
- (void)registerAPN {
    if (@available(iOS 10.0, *)) { // iOS10 以上
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if(granted){
                debugLog(@"granted");
            }else{
            }
        }];
        // 可以通过 getNotificationSettingsWithCompletionHandler 获取权限设置
        //之前注册推送服务，用户点击了同意还是不同意，以及用户之后又做了怎样的更改我们都无从得知，现在 apple 开放了这个 API，我们可以直接获取到用户的设定信息了。注意UNNotificationSettings是只读对象哦，不能直接修改！
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"settings ========%@",settings);
        }];
    } else {// iOS8.0 以上
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    }
}

- (void)setupNetwork{
    AFNetworkReachabilityManager *netWorkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [netWorkReachabilityManager startMonitoring];
    [netWorkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
            {
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = @"网络连接已断开";
                [hud hideAnimated:YES afterDelay:1];
                [self notifyNetworkDisConnected];
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                // 获取手机网络类型
                CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
                NSString *currentStatus = info.currentRadioAccessTechnology;
                if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {
                    _netconnType = @"GPRS";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyEdge"]) {
                    _netconnType = @"2.75G EDGE";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){
                    _netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSDPA"]){
                    _netconnType = @"3.5G HSDPA";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSUPA"]){
                    _netconnType = @"3.5G HSUPA";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){
                    _netconnType = @"2G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){
                    _netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){
                    _netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){
                    _netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyeHRPD"]){
                    _netconnType = @"HRPD";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){
                    _netconnType = @"4G";
                }
                [self notifyNetworkConnected];
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                _netconnType = @"Wifi";
                [self notifyNetworkConnected];
            }
                break;
            default:{
                
            }
                break;
        }
    }];
}
- (void)notifyNetworkConnected{
    self.isNetworkConnenct = YES;
    NSMutableDictionary * paramDevice = [NSMutableDictionary dictionary];
    paramDevice[@"macId"] = [SystemDeviceTool getUUID];
    paramDevice[@"macAddr"] = [self MacAddress];
    paramDevice[@"manufacturer"] = @"苹果";
    paramDevice[@"modelNum"] = @(1); //手机型号
    //    paramDevice[@"modelNum"] = [SystemDeviceTool getCurrentDeviceModel];
    paramDevice[@"ipAddr"] = [[ZJPhoneIPAddress new] getIPAddress];
    paramDevice[@"imei"] = @""; // IMEI
    paramDevice[@"version"] = [SystemDeviceTool getCurrentDeviceModel]; // 版本
    paramDevice[@"ram"] = [self getFreeDiskspace]; // 内存
    paramDevice[@"wllx"] = _netconnType; // 网络类型
    paramDevice[@"wfzt"] = [self isWiFiEnabled]?@(1):@(0); // wifi状态
    CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [telephonyInfo subscriberCellularProvider];
    NSString *currentCountry=[carrier carrierName];
    paramDevice[@"yyshang"] = currentCountry; //运营商
    paramDevice[@"agent"] = [self getUA]; // user-agent信息
    paramDevice[@"wlqx"] = @([self getWifiPrivileage]); // 网络权限
    // [[[UIDevice currentDevice] identifierForVendor] UUIDString]
    paramDevice[@"xlh"] = @"";  // 序列号
    paramDevice[@"wifiIp"] = [[ZJPhoneIPAddress new] getIPAddress]; // 无线局域网地址
    paramDevice[@"pNum"] = @(0); //
    paramDevice[@"wifiName"] = [self returnWifiName]; // 热点名称
    paramDevice[@"iccid"] = @""; //
    paramDevice[@"meid"] = @"";
    paramDevice[@"seid"] = @"";
    [[PLRequestManage sharedInstance] httpRequestWithUrl:WEBSOCKETWITH(url_upload_device) Type:RequestPost parameters:paramDevice completeHandle:^(id  _Nullable responseObject, NSError *error) {
        if (!error) {
        } else {
        }
    }];
    if ([UserLocal isLogin]) {
        NSMutableDictionary * paramSocket = [NSMutableDictionary dictionary];
        paramSocket[@"macId"] = [SystemDeviceTool getUUID];
        paramSocket[@"userId"] =[[UserLocal sharedInstance] currentUserInfo].phone;
        paramSocket[@"flag"] = @(0);
        [[PLRequestManage sharedInstance] httpRequestWithUrl:WEBSOCKETWITH(url_loginWebsocket) Type:RequestPost parameters:paramSocket completeHandle:^(id  _Nullable responseObject, NSError *error) {
            if (!error) {
            }else{
            }
        }];
    }else{
        NSMutableDictionary * paramSocket = [NSMutableDictionary dictionary];
        paramSocket[@"macId"] = [SystemDeviceTool getUUID];
        paramSocket[@"userId"] =[[UserLocal sharedInstance] currentUserInfo].phone;
        paramSocket[@"flag"] = @(1);
        [[PLRequestManage sharedInstance] httpRequestWithUrl:WEBSOCKETWITH(url_loginWebsocket) Type:RequestPost parameters:paramSocket completeHandle:^(id  _Nullable responseObject, NSError *error) {
            if (!error) {
            }else{
            }
        }];
    }
}
- (void)notifyNetworkDisConnected{
    self.isNetworkConnenct = NO;
    //    [[NSNotificationCenter defaultCenter] postNotificationName:kNotifyNetworkDisConnected object:nil];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    // 防止websocket断开https://www.cnblogs.com/liuhuakun/p/6704762.html
    [self beginTask];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    self.number = 0;
    if (@available(iOS 10.0, *)) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f repeats:YES block:^(NSTimer * _Nonnull timer) {
            self.number++;
            [UIApplication sharedApplication].applicationIconBadgeNumber = self.number;
            if (self.number == 9) {
                [self.timer invalidate];
            }
        }];
    } else {
    }
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
/// app进入后台后保持运行
- (void)beginTask {
    _backIden = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        //如果在系统规定时间3分钟内任务还没有完成，在时间到之前会调用到这个方法
        [self endBack];
    }];
}
/// 结束后台运行，让app挂起
- (void)endBack {
    //切记endBackgroundTask要和beginBackgroundTaskWithExpirationHandler成对出现
    [[UIApplication sharedApplication] endBackgroundTask:_backIden];
    _backIden = UIBackgroundTaskInvalid;
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    debugLog(@"willPresentNotification");
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
{
    debugLog(@"local notification");
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        debugLog(@"远程通知");
    }else {
        UNNotificationRequest *request = response.notification.request; // 收到推送的请求
        UNNotificationContent *content = request.content; // 收到推送的消息内容
        NSNumber *badge = content.badge;  // 推送消息的角标
        NSString *body = content.body;    // 推送消息体
        UNNotificationSound *sound = content.sound;  // 推送消息的声音
        NSString *subtitle = content.subtitle;  // 推送消息的副标题
        NSString *title = content.title;  // 推送消息的标题
        debugLog(@"iOS10 收到本地通知:{\\\\nbody:%@，\\\\ntitle:%@,\\\\nsubtitle:%@,\\\\nbadge：%@，\\\\nsound：%@，\\\\nuserInfo：%@\\\\n}",body,title,subtitle,badge,sound,userInfo);
    }
    SLLoanMessageModel *msgM = [SLLoanMessageModel mj_objectWithKeyValues:userInfo];
    SLMessageDetailViewController *detailVC = [SLMessageDetailViewController new];
    [detailVC setMessageDetailModel:msgM];
    [getDelegate().masterNavigationController pushViewController:detailVC animated:YES];
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:[UserLocal token] forKey:@"token"];
    [param setObject:msgM.mId forKey:@"messageId"];
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_update_status) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        if (!error) {
        }
    }];
    completionHandler();  // 系统要求执行这个方法
}
#pragma mark -
- (BOOL)isNetworkAvailable
{
    return _isNetworkConnenct;
}
- (void)addLocalNotice:(SLLoanMessageModel *)model {
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = model.title;
        content.body = model.content;
        content.userInfo = model.mj_keyValues;
        // 默认声音
        //    content.sound = [UNNotificationSound defaultSound];
        // 添加自定义声音
//        content.sound = [UNNotificationSound soundNamed:@"Alert_ActivityGoalAttained_Salient_Haptic.caf"];
        // 角标 （我这里测试的角标无效，暂时没找到原因）
//        content.badge = @1;
        // 多少秒后发送,可以将固定的日期转化为时间
        NSTimeInterval time = [[NSDate dateWithTimeIntervalSinceNow:1] timeIntervalSinceNow];
        //        NSTimeInterval time = 10;
        // repeats，是否重复，如果重复的话时间必须大于60s，要不会报错
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:time repeats:NO];
        // 添加通知的标识符，可以用于移除，更新等操作
        NSString *identifier = model.mId;
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
        [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
            debugLog(@"成功添加推送");
        }];
    }else {
        UILocalNotification *notif = [[UILocalNotification alloc] init];
        notif.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
        notif.alertBody = @"";
        notif.userInfo = @{@"noticeId":@"00001"};
        notif.applicationIconBadgeNumber = 1;
        notif.soundName = UILocalNotificationDefaultSoundName;
//        notif.repeatInterval = NSCalendarUnitWeekOfYear;
        [[UIApplication sharedApplication] scheduleLocalNotification:notif];
    }
}

#pragma mark - 获取当前连接wifi信息
- (int)getWifiPrivileage{
    int wifiP = 1;
    CTCellularData *cellularData = [[CTCellularData alloc]init];
    CTCellularDataRestrictedState state = cellularData.restrictedState;
    switch (state) {
        case kCTCellularDataRestricted:
            NSLog(@"Restricrted");
            break;
        case kCTCellularDataNotRestricted:
            NSLog(@"Not Restricted");
            break;
        case kCTCellularDataRestrictedStateUnknown:
            NSLog(@"Unknown");
            break;
        default:
            break;
    }
    return wifiP;
}

- (NSString *)returnWifiName
{
    NSString *wifiName = @"Not Found";
    CFArrayRef myArray = CNCopySupportedInterfaces();
    if (myArray != nil) {
        CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        if (myDict != nil) {
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            wifiName = [dict valueForKey:@"SSID"];}
    }
    return wifiName;
}
- (NSString *)MacAddress
{
    NSArray *ifs = CFBridgingRelease(CNCopySupportedInterfaces());
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((CFStringRef)ifnam);
        if (info && [info count]) {
            break;
        }
    }
    NSDictionary *dic = (NSDictionary *)info;
    NSString *bssid = [dic objectForKey:@"BSSID"];
    return bssid;
}
- (NSString *)getUA{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *userAgentString = [webView stringByEvaluatingJavaScriptFromString:
                                @"navigator.userAgent"];
    debugLog(@"useragent = %@",userAgentString);
    return userAgentString;
}
//返回存储内存占用比例
- (NSString *)getFreeDiskspace{
    float totalSpace;
    float totalFreeSpace=0.f;
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
    NSString *freeString = @"";
    if (dictionary) {
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;
        totalFreeSpace = [freeFileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;
        //totalString、freeString是定义两个全局变量 进度条上显示大小数据用
//        totalString = [self getFileSizeString:[fileSystemSizeInBytes floatValue]];
        freeString = [self getFileSizeString:[freeFileSystemSizeInBytes floatValue]];
    } else {
        debugLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], [error code]);
    }
    return freeString;
}
-(NSString *)getFileSizeString:(CGFloat)size
{
    if (size>1024*1024*1024){
        return [NSString stringWithFormat:@"%.1fG",size/1024/1024/1024];//大于1G，则转化成G单位的字符串
    }else if(size<1024*1024*1024&&size>=1024*1024)//大于1M，则转化成M单位的字符串
    {
        return [NSString stringWithFormat:@"%.1fM",size/1024/1024];
    }
    else if(size>=1024&&size<1024*1024) //不到1M,但是超过了1KB，则转化成KB单位
    {
        return [NSString stringWithFormat:@"%.1fK",size/1024];
    }
    else//剩下的都是小于1K的，则转化成B单位
    {
        return [NSString stringWithFormat:@"%.1fB",size];
    }
}
- (BOOL)isWiFiEnabled {
    NSCountedSet * cset = [[NSCountedSet alloc] init];
    struct ifaddrs *interfaces;
    if( ! getifaddrs(&interfaces) ) {
        for( struct ifaddrs *interface = interfaces; interface; interface = interface->ifa_next) {
            if ( (interface->ifa_flags & IFF_UP) == IFF_UP ) {
                [cset addObject:[NSString stringWithUTF8String:interface->ifa_name]];
            }
        }
    }
    return [cset countForObject:@"awdl0"] > 1 ? YES : NO;
}
@end




